import Array._

class RoutingTable(nodeId : String){
	var table = ofDim[NodeEntry](32,16)
	var lastModified = System.currentTimeMillis()  
	
	def get(row : Integer, col : Integer) : NodeEntry = {
	  table(row)(col)  
	}
	
	def add(node : NodeEntry){
	  val row = Utils.shl(node.getNodeId, nodeId)
	  if (row < 32){
	    val col = Utils.getKeyDigitValue(node.getNodeId, row)
	  
	    if (table(row)(col) == null){
	      table(row)(col) = node
	      var lastModified = System.currentTimeMillis()  
	    }
	  }
	}
	
	def print(){
	  println("table for: " + nodeId)
	  for (i <- 0 to table.length - 1){
	    var s = ""
	    for (j <- 0 to table(i).length - 1){
	      if (table(i)(j) != null){
	        s = s + table(i)(j).getNodeId + " , "
	      }
	      else{
	        s = s + "null , "
	      }
	    }
	    println(s)
	  }
	}
	
	def findCloserNode(key : String, minPrefix : Integer) : NodeEntry = {
	  var result = new NodeEntry
	  val diff = Utils.getNodeDiff(key, nodeId)
	  
	  var i = minPrefix
	  while (i < table.length){
	    var j = 0
	    while (j < table(i).length){
	      val e = table(i)(j)
	      if (e != null){
	        val thisDiff = Utils.getNodeDiff(key, e.getNodeId)
	        if (thisDiff.compareTo(diff) < 0){
	          result = e
	          j = table(i).length
	          i = table.length -1
	        }
	      }
	      j += 1
	    }
	    i += 1
	  }
	  
	  result
	}
	
	def toJson() : String = {
	  //var json = "{"
	  //json += "\"nodeId\": \"" + nodeId + "\","
	  
	  //var json += "\"table\":["
	    
	  var json = "["
	  for (i <- 0 to table.length-1){
	    json += "["
	    for (j <- 0 to table(i).length-1){
	      if (table(i)(j) != null){
	      	json += table(i)(j).toJson + ","
	      }
	      else{
	      	json += "{},"
	      }
	    }
	    if (json.last == ','){ 
	      json = json.substring(0, json.length()-1)
	    }
	    json += "]"
	    if (i < table.length-1) { json += ","}  
	  }
	  
	  json += "]"  
	  //json += "}"  
	  json  
	}
}